import {Effect, Reducer} from 'umi';
import {ProductBasicInfoType, ProductInfoType} from './data.d';
import {listGroupByCategory, categoryProductList, getProductInfo, applyOrder} from './service'

export interface ProductDataState {
  products?: ProductInfoType[];
  productBasicInfos?: ProductBasicInfoType[];
  productInfo: ProductInfoType;
}

// 顶层接口定义，用来约束model必备条件
export interface ProductModelType {
  namespace: string;
  state: ProductDataState
  reducers: {
    setProducts: Reducer<any>;
    setProductBasicInfos: Reducer<any>;
    setProductInfo: Reducer<any>
  };
  effects: {
    getProducts: Effect,
    getProductBasicInfos: Effect
    getProductInfo: Effect,
    createApplyOrder: Effect,
  }
}

const Model: ProductModelType = {
  namespace: 'productWorkplace',
  state: {
    products: [],
    productBasicInfos: [],
    productInfo: {},
  },
  reducers: {
    // 第一个参数是更新前的state对象, 第二个是传递参数
    setProducts(state, {payload}) {
      // 返回更新后的state对象
      return {
        products: payload.payload,
      };
    },
    setProductBasicInfos(state, {payload}) {
      return {
        ...state,
        productBasicInfos: payload.payload,
      };
    },
    setProductInfo(state, {payload}) {
      return {
        ...state,
        productInfo: payload.payload,
      };
    },
  },
  // 新增effects配置，用于异步加载数
  effects: {
    // 第一个是请求参数
    // call异步调用， pull指定一个action
    * getProducts({params}, {call, put}) {
      // 执行请求
      const response = yield call(listGroupByCategory, params);
      yield put({ // 调用reducers中的方法
        type: 'setProducts',   // 方法名称
        payload: response // 传递给renducer 方法的数据
      });
    },
    * getProductBasicInfos({params}, {call, put}) {
      const response = yield call(categoryProductList, params);
      yield put({
        type: 'setProductBasicInfos',
        payload: response
      });
    },
    * getProductInfo({params}, {call, put}) {
      const response = yield call(getProductInfo, params);
      yield put({
        type: 'setProductInfo',
        payload: response
      });
    },
    * createApplyOrder({params}, {call, put}) {
      const response = yield call(applyOrder, params);
      yield put({
        type: 'setProductInfo',
        payload: response
      });
    }
  },
};


export default Model;
